using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace CodePlex.Resourceful.Json
{

    public class JsonObject : JsonBase, IEnumerable<string>
    {
        private readonly Dictionary<string, object> _values;

        public JsonObject(JsonReader reader)
        {
            if (reader.TokenType == JsonToken.None)
            {
                reader.Read();  // none
            }
            
            

            _values = ReadObjectValues(reader);

        }

        public T Get<T>(string propertyName)
        {
            
           
            object rt = _values[propertyName];

            if (rt == null)
            {
                return default(T);
            }

            Type actualType = rt.GetType();

            // so we do not have to support iconvertible...
            if (actualType.Equals(typeof(JsonArray)) || actualType.Equals(typeof(JsonObject)))
            {
                return (T)rt;
            }

            return Utils.ChangeType<T>(rt);
        }


        private static Dictionary<string, object> ReadObjectValues(JsonReader reader)
        {
            reader.Read();  // startobject

            Dictionary<string, object> values = new Dictionary<string, object>();

            while (reader.TokenType != JsonToken.EndObject)
            {

                if (reader.TokenType == JsonToken.PropertyName)
                {
                    string name = reader.Value as string;

                    reader.Read();  // propertyname

                    object value = ReadUnknown(reader);

                    values[name] = value;
                }
                else
                {
                    throw new NotSupportedException(reader.TokenType.ToString());
                }
            }

            reader.Read();  // endobject

            return values;
        }


       

        public IEnumerator<string> GetEnumerator()
        {
            return _values.Keys.GetEnumerator();
        }

     


        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }




        
    }
}
